﻿using WholesaleOnline.Contract;
using WholesaleOnline.Controller.Extension;
using WholesaleOnline.Controller.Request;
using WholesaleOnline.Controller.Routing;
using WholesaleOnline.Controller.Storage;
using WholesaleOnline.DataContract.Messaging;

namespace WholesaleOnline.Controller.Handlers
{
    public class GetKeywordsHandler : RequestHandler
    {
        private IInventoryService m_inventoryService = null;

        public GetKeywordsHandler(IHttpStorage storage, IInventoryService inventoryService)
            : base(Routes.GET_KEYWORDS, storage)
        {
            m_inventoryService = inventoryService;
        }

        public override void Handle(WebRequest webRequest)
        {
            if (Route.Matches(webRequest))
            {
                string keyword = webRequest.QueryArguments.ExtractFor<string>("q");
                if (string.IsNullOrEmpty(keyword))
                {
                    Storage.Add(HttpStorageKeys.Json, "[]");
                }
                else
                {
                    GetKeywordsRequest request = new GetKeywordsRequest
                    {
                        Keyword = keyword,
                        Count = 10
                    };

                    GetKeywordsResponse response = m_inventoryService.GetKeywords(request);
                    if (response.Success)
                    {
                        Storage.Add(HttpStorageKeys.Json, response.Keywords.ConvertToComboboxJson());
                    }
                    else
                    {
                        Storage.Add(HttpStorageKeys.Exception, response.Message);
                        Storage.Add(HttpStorageKeys.Json, "[]");
                    }
                }
            }
            else
            {
                base.NextHandler.Handle(webRequest);
            }
        }
    }
}
